package com.lk.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * @author : lk
 * @date 2021/11/10 10:58
 * @description : TODO
 * @since 1.0
 **/
@Component
@Slf4j
public class RabbitMqUtil {


    @Resource
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     *
     * 路由键是和队列进行绑定
     * @param exchange    交换机的名称
     * @param routingKey  路由key的名称
     * @param messageBody 消息体 json形式
     */
    public void sendMessage(String exchange, String routingKey, Object messageBody) {
        try {
            String value = objectMapper.writeValueAsString(messageBody);
            Message message = MessageBuilder.withBody(value.getBytes()) // 消息正文
                    .setMessageId(IdUtil.getSimpleId())// 设置全局的唯一ID避免消息的重复消费
                    .setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8").build();// 设置内容类型
            rabbitTemplate.convertAndSend(exchange, routingKey, message);
        } catch (Exception e) {
            log.error("e", e);
        }

    }
}
